﻿//-----------------------------------------------------------------------
// <copyright file="EditorModule.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace App.Modules.Editor
{
    using System;
    using System.Collections.Generic;
    using App.Modules.ChangeTrack;
    using App.Modules.Message;
    using App.Modules.Render;
    using App.Modules.Scene;
    using App.Modules.Tool;
    using TileTool.Action.Message;
    using TileTool.Base.Editor.Grid;
    using TileTool.Base.Editor.Transform;
    using TileTool.Editor.Command;
    using TileTool.Editor.Tool.Transform;
    using TileTool.Editor.Transform;
    using TileTool.Log;
    using TileTool.Message;
    using TileTool.Scene;
    using TileTool.Scene.Action;
    using TileTool.Scene.Entity;
    using TileTool.Scene.Message;
    using TileTool.Tool;

    /// <summary>
    /// Application editor module.
    /// </summary>
    public class EditorModule : Module
    {
        #region Constants - Private

        /// <summary>
        /// Log message group.
        /// </summary>
        private const string LogGroup = "EditorModule";

        /// <summary>
        /// Default grid size.
        /// </summary>
        private const int DefaultGridSize = 16;

        #endregion

        #region Fields - Private

        /// <summary>
        /// Grid we are using.
        /// </summary>
        private Grid grid;

        /// <summary>
        /// Snap state we are using.
        /// </summary>
        private SnapState snapState;

        /// <summary>
        /// Transform state we manage.
        /// </summary>
        private TransformState transformState;

        #endregion

        #region Properties - Public

        /// <summary>
        /// Gets the transform state for the editor.
        /// </summary>
        public ITransformState State
        {
            get
            {
                return this.transformState;
            }
        }

        #endregion

        #region Methods - Public

        /// <summary>
        /// Called when the application is starting up.
        /// </summary>
        public override void Startup()
        {
            LogSystem.LogStartup(LogGroup, "Starting...");

            SceneModule sceneModule = GetModule<SceneModule>();
            MessageModule messageModule = GetModule<MessageModule>();
            RenderModule renderModule = GetModule<RenderModule>();

            this.grid = new Grid();
            this.grid.Size = DefaultGridSize;

            this.snapState = new SnapState();

            this.transformState = new TransformState(sceneModule.Scene);
            this.transformState.Grid = this.grid;
            this.transformState.SnapState = this.snapState;

            renderModule.Grid = this.grid;

            this.SetupEditorToolFixup();

            base.Startup();
        }

        /// <summary>
        /// Register for messages.
        /// </summary>
        public override void RegisterForMessages()
        {
            base.RegisterForMessages();

            SceneModule sceneModule = GetModule<SceneModule>();
            ChangeTrackModule changeModule = GetModule<ChangeTrackModule>();
            MessageModule messageModule = GetModule<MessageModule>();
            ISceneManager sceneManager = sceneModule.Scene;
            MessageRouter router = messageModule.MessageRouter;
            SceneMessageFilter filter = new SceneMessageFilter(sceneManager);

            router.RegisterForMessage<SceneSelectionChangedMessage>(
                this.HandleSceneSelectionChangedMessage,
                MessageHandlerPriority.Default,
                filter);

            router.RegisterForMessage<SceneClearedMessage>(
                this.HandleSceneClearedMessage,
                MessageHandlerPriority.Default,
                filter);

            router.RegisterForMessage<CommandIdMessage>(
                this.HandleToggleSnapToGridCommandMessage,
                MessageHandlerPriority.Default,
                new CommandIdMessageFilter(EditorCommandIds.ToggleSnapToGridCommand));

            router.RegisterForMessage<CommandIdMessage>(
                this.HandleSetCoordinateSystemCommandMessage,
                MessageHandlerPriority.Default,
                new CommandIdMessageFilter(EditorCommandIds.SetCoordinateSystemCommand));

            router.RegisterForMessage<CommandIdMessage>(
                this.HandleToggleTranslateSnapCommandMessage,
                MessageHandlerPriority.Default,
                new CommandIdMessageFilter(EditorCommandIds.ToggleTranslateSnapCommand));

            router.RegisterForMessage<CommandIdMessage>(
                this.HandleToggleRotateSnapCommandMessage,
                MessageHandlerPriority.Default,
                new CommandIdMessageFilter(EditorCommandIds.ToggleRotateSnapCommand));

            changeModule.EntitiesChanged += this.ChangeTrackHandleEntityChanged;
        }

        /// <summary>
        /// Unregister for messages.
        /// </summary>
        public override void UnregisterForMessages()
        {
            base.UnregisterForMessages();

            SceneModule sceneModule = GetModule<SceneModule>();
            ChangeTrackModule changeModule = GetModule<ChangeTrackModule>();
            MessageModule messageModule = GetModule<MessageModule>();
            MessageRouter router = messageModule.MessageRouter;
            ISceneManager sceneManager = sceneModule.Scene;

            router.UnregisterForMessage<SceneSelectionChangedMessage>(this.HandleSceneSelectionChangedMessage);
            router.UnregisterForMessage<SceneClearedMessage>(this.HandleSceneClearedMessage);
            router.UnregisterForMessage<CommandIdMessage>(this.HandleToggleSnapToGridCommandMessage);
            router.UnregisterForMessage<CommandIdMessage>(this.HandleSetCoordinateSystemCommandMessage);
            router.UnregisterForMessage<CommandIdMessage>(this.HandleToggleTranslateSnapCommandMessage);
            router.UnregisterForMessage<CommandIdMessage>(this.HandleToggleRotateSnapCommandMessage);

            changeModule.EntitiesChanged -= this.ChangeTrackHandleEntityChanged;
        }

        /// <summary>
        /// Toggle the current grid snap state.
        /// </summary>
        public void ToggleGridSnap()
        {
            this.SetGridSnap(!this.snapState.SnapToGrid);
        }

        /// <summary>
        /// Set the state of grid snap.
        /// </summary>
        /// <param name="snap">true if we want to enable grid snap.</param>
        public void SetGridSnap(bool snap)
        {
            this.snapState.SnapToGrid = snap;

            SnapStateChangedMessage msg = new SnapStateChangedMessage();

            msg.SnapState = this.snapState;

            this.SendMessage(msg);
        }

        /// <summary>
        /// Set the state of translate snap.
        /// </summary>
        /// <param name="snap">true if we want to enable translate snap.</param>
        public void SetTranslateSnap(bool snap)
        {
            this.snapState.TranslateSnap = snap;

            SnapStateChangedMessage msg = new SnapStateChangedMessage();

            msg.SnapState = this.snapState;

            this.SendMessage(msg);
        }

        /// <summary>
        /// Set the state of rotate snap.
        /// </summary>
        /// <param name="snap">true if we want to enable rotate snap.</param>
        public void SetRotateSnap(bool snap)
        {
            this.snapState.RotateSnap = snap;

            SnapStateChangedMessage msg = new SnapStateChangedMessage();

            msg.SnapState = this.snapState;

            this.SendMessage(msg);
        }

        /// <summary>
        /// Deltes the currently selected objects.
        /// </summary>
        public void DeleteSelection()
        {
            SceneModule sceneModule = GetModule<SceneModule>();
            ISceneManager scene = sceneModule.Scene;
            IEntityCollection selection = scene.Selection;

            if (selection.Count == 0)
            {
                return;
            }

            AddRemoveEntityAction removeAction = new AddRemoveEntityAction(scene, selection, false);

            removeAction.Do();

            this.SendMessage(new ActionMessage(removeAction));
        }

        #endregion

        #region Methods - Private - Tool fixup

        /// <summary>
        /// Setup the fixup function we use to setup editor tools properly.
        /// </summary>
        private void SetupEditorToolFixup()
        {
            ToolModule toolModule = GetModule<ToolModule>();
            IToolManager toolManager = toolModule.ToolManager;

            toolManager.Installed += (ITool tool) =>
                {
                    IManipulatorTool transformTool = tool as IManipulatorTool;
                    if (transformTool == null)
                    {
                        return;
                    }

                    transformTool.State = State;
                };

            toolManager.Uninstalled += (ITool tool) =>
                {
                    IManipulatorTool transformTool = tool as IManipulatorTool;
                    if (transformTool == null)
                    {
                        return;
                    }

                    transformTool.State = null;
                };
        }

        #endregion

        #region Methods - Private - Entity change tracking

        /// <summary>
        /// Handle entities changing.
        /// </summary>
        /// <param name="changes">Entity changes that have happened.</param>
        private void ChangeTrackHandleEntityChanged(IEnumerable<EntityChangedEventArgs> changes)
        {
            foreach (EntityChangedEventArgs change in changes)
            {
                IEntity entity = change.Entity;
                if (entity.Selected)
                {
                    this.transformState.Update();
                    break;
                }
            }
        }

        #endregion

        #region Methods - Private - Scene message handlers

        /// <summary>
        /// Handle a selection changed message.
        /// </summary>
        /// <param name="msg">Message to handle.</param>
        /// <returns>MessageHandlerResult for if we handled the message.</returns>
        private MessageHandlerResult HandleSceneClearedMessage(SceneClearedMessage msg)
        {
            this.transformState.Update();

            return MessageHandlerResult.Ignored;
        }

        /// <summary>
        /// Handle a selection changed message.
        /// </summary>
        /// <param name="msg">Message to handle.</param>
        /// <returns>MessageHandlerResult for if we handled the message.</returns>
        private MessageHandlerResult HandleSceneSelectionChangedMessage(SceneSelectionChangedMessage msg)
        {
            this.transformState.Update();

            return MessageHandlerResult.Ignored;
        }

        #endregion

        #region Methods - Private - Message handlers

        /// <summary>
        /// Handle a snap to grid toggle command ID message.
        /// </summary>
        /// <param name="message">Command ID message to handle.</param>
        /// <returns>Returns if the message was handled or not.</returns>
        private MessageHandlerResult HandleToggleSnapToGridCommandMessage(CommandIdMessage message)
        {
            this.SetGridSnap(!this.snapState.SnapToGrid);

            return MessageHandlerResult.Ignored;
        }

        /// <summary>
        /// Handle a set coordinate system command ID message.
        /// </summary>
        /// <param name="message">Command ID message to handle.</param>
        /// <returns>Returns if the message was handled or not.</returns>
        private MessageHandlerResult HandleSetCoordinateSystemCommandMessage(CommandIdMessage message)
        {
            object[] args = message.Params;

            // $TODO - this whole process is really stupid. Move messages away from interfaces.
            // This experiment has failed and isn't worth the effort.
            if (args == null || args.Length == 0)
            {
                return MessageHandlerResult.Ignored;
            }

            if (args[0] == null)
            {
                return MessageHandlerResult.Ignored;
            }

            if (!Enum.IsDefined(typeof(CoordinateSystem), args[0]))
            {
                return MessageHandlerResult.Ignored;
            }

            CoordinateSystem system = (CoordinateSystem)args[0];

            this.transformState.System = system;

            return MessageHandlerResult.Ignored;
        }

        /// <summary>
        /// Handle a translate snap toggle command ID message.
        /// </summary>
        /// <param name="message">Command ID message to handle.</param>
        /// <returns>Returns if the message was handled or not.</returns>
        private MessageHandlerResult HandleToggleTranslateSnapCommandMessage(CommandIdMessage message)
        {
            this.SetTranslateSnap(!this.snapState.TranslateSnap);

            return MessageHandlerResult.Ignored;
        }

        /// <summary>
        /// Handle a rotate snap toggle command ID message.
        /// </summary>
        /// <param name="message">Command ID message to handle.</param>
        /// <returns>Returns if the message was handled or not.</returns>
        private MessageHandlerResult HandleToggleRotateSnapCommandMessage(CommandIdMessage message)
        {
            this.SetRotateSnap(!this.snapState.RotateSnap);

            return MessageHandlerResult.Ignored;
        }

        #endregion
    }
}
